package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityTimeCalculateBinding;
import stark.common.basic.event.EventStatProxy;

public class TimeCalculateActivity extends BaseAc<ActivityTimeCalculateBinding> {

    private Dialog mySelDateDialog, mySelTimeDialog, myTimeUnitDialog;
    private WheelView wheelView1, wheelView2, wheelView3, wheelView4, wheelView5, wheelView6, wheelView7;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private List<String> listUnit = new ArrayList<>();//时间单位
    private int selPosition;


    @Override
    protected int onCreate() {
        return R.layout.activity_time_calculate;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivTimeCalculateBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvInitialDate.setOnClickListener(this);
        mDataBinding.tvInitialTime.setOnClickListener(this);
        mDataBinding.tvUnit.setOnClickListener(this);
        mDataBinding.tvCalculate.setOnClickListener(this);
        mDataBinding.tvReset.setOnClickListener(this);

        mDataBinding.etNum.addTextChangedListener(new TextWatcher() {

            private boolean ignore = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (ignore) {
                    ignore = false;
                    return;
                }

                String text = s.toString();
                String cleanText = "";
                if (text.length() == 1) {
                    cleanText = text.replaceAll("[^\\d-]", "");
                } else {
                    if (text.lastIndexOf('-') == 0) {
                        cleanText = "-" + text.replaceAll("[^\\d]", "");
                    } else {
                        cleanText = text.replaceAll("[^\\d]", "");
                    }
                }
                if (!text.equals(cleanText)) {
                    ignore = true;
                    mDataBinding.etNum.setText(cleanText);
                    mDataBinding.etNum.setSelection(cleanText.length());
                }
            }
        });
        //选择日期弹框
        selDateDialog();
        //选择时间弹框
        selTimeDialog();
        //选择时间单位弹框
        selTimeUnitDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvInitialDate://初始日期
                mySelDateDialog.show();
                break;
            case R.id.tvInitialTime://初始时间
                mySelTimeDialog.show();
                break;
            case R.id.tvUnit://时间单位
                myTimeUnitDialog.show();
                break;
            case R.id.tvCalculate://计算
                calculate();
                break;
            case R.id.tvReset://重置
                mDataBinding.tvInitialDate.setText("");
                mDataBinding.tvInitialTime.setText("");
                mDataBinding.etNum.setText("");
                mDataBinding.tvUnit.setText("");
                mDataBinding.tvResult.setText("");
                break;
            //选择日期弹框
            case R.id.tvDialogSelDateCancel://取消
                mySelDateDialog.dismiss();
                break;
            case R.id.tvDialogSelDateRight://确定
                mySelDateDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                int day = wheelView3.getCurrentItem() + 1;
                String selDate = year + "年" + (moon < 10 ? "0" + moon : moon) + "月" + (day < 10 ? "0" + day : day + "日");
                mDataBinding.tvInitialDate.setText(selDate);
                break;
            //选择时间弹框
            case R.id.tvDialogSelTimeCancel://取消
                mySelTimeDialog.dismiss();
                break;
            case R.id.tvDialogSelTimeRight://确定
                mySelTimeDialog.dismiss();
                int hour = wheelView4.getCurrentItem();
                int minute = wheelView5.getCurrentItem();
                int second = wheelView6.getCurrentItem();
                String selTime = hour + "点" + minute + "分" + second + "秒";
                mDataBinding.tvInitialTime.setText(selTime);
                break;
            //选择时间单位弹框
            case R.id.tvDialogTimeUnitCancel://取消
                myTimeUnitDialog.dismiss();
                break;
            case R.id.tvDialogTimeUnitRight://确定
                myTimeUnitDialog.dismiss();
                selPosition = wheelView7.getCurrentItem();
                mDataBinding.tvUnit.setText(listUnit.get(selPosition));
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void calculate() {
        String date = mDataBinding.tvInitialDate.getText().toString();
        if (TextUtils.isEmpty(date)) {
            ToastUtils.showShort(getString(R.string.please_sel_initial_date));
            return;
        }
        String time = mDataBinding.tvInitialTime.getText().toString();
        if (TextUtils.isEmpty(time)) {
            ToastUtils.showShort(getString(R.string.please_sel_initial_time));
            return;
        }
        String unit = mDataBinding.tvUnit.getText().toString();
        if (TextUtils.isEmpty(unit)) {
            ToastUtils.showShort(getString(R.string.please_sel_time_unit));
            return;
        }
        String selTime = date + " " + time;
        long startTime = TimeUtils.string2Millis(selTime, new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒"));
        String str = mDataBinding.etNum.getText().toString();
        if (TextUtils.isEmpty(str)) {
            ToastUtils.showShort(getString(R.string.please_input_add_num));
            return;
        }
        int num = Integer.parseInt(str);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(startTime));
        if (selPosition == 0) {
            calendar.set(calendar.get(Calendar.YEAR) + num, calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        } else if (selPosition == 1) {
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + num, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        } else if (selPosition == 2) {
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) + num, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        } else if (selPosition == 3) {
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR) + num, calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
        }
        mDataBinding.tvResult.setText(TimeUtils.millis2String(calendar.getTimeInMillis(), new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒")));
    }


    //选择日期弹框
    private void selDateDialog() {
        mySelDateDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_date, null);
        mySelDateDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelDateDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelDateCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelDateRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        wheelView3 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView1.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(18);
        wheelView2.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView2.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(18);
        wheelView3.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView3.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView3.setLineSpacingMultiplier(2.5f);
        wheelView3.setDividerType(WheelView.DividerType.WRAP);
        wheelView3.setCurrentItem(0);
        wheelView3.setItemsVisibleCount(5);
        wheelView3.setCyclic(true);
        wheelView3.setTextSize(18);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);
        setDayDate(31);//日 默认显示1月 共31天

        //监听月份滚动选择
        wheelView2.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                index = index + 1;
                if (index == 1 || index == 3 || index == 5 || index == 7 || index == 8 || index == 10 || index == 12) {
                    //大月31天
                    setDayDate(31);
                } else if (index == 2) {
                    //2月判断是闰(29)还是平(28)
                    if (TimeUtils.isLeapYear(TimeUtils.getNowString(format), format)) {
                        setDayDate(29);
                    } else {
                        setDayDate(28);
                    }
                } else {
                    //小月30天
                    setDayDate(30);
                }
            }
        });
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        int day = Integer.parseInt(split[2]);//日
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
        wheelView3.setCurrentItem(day - 1);
    }

    //选择时间弹框
    private void selTimeDialog() {
        mySelTimeDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_time, null);
        mySelTimeDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelTimeDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelTimeCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelTimeRight);
        wheelView4 = inflate.findViewById(R.id.wheel_view1);
        wheelView5 = inflate.findViewById(R.id.wheel_view2);
        wheelView6 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView4.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView4.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView4.setLineSpacingMultiplier(2.5f);
        wheelView4.setDividerType(WheelView.DividerType.WRAP);
        wheelView4.setCurrentItem(0);
        wheelView4.setItemsVisibleCount(5);
        wheelView4.setCyclic(true);
        wheelView4.setTextSize(18);
        wheelView5.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView5.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView5.setLineSpacingMultiplier(2.5f);
        wheelView5.setDividerType(WheelView.DividerType.WRAP);
        wheelView5.setCurrentItem(0);
        wheelView5.setItemsVisibleCount(5);
        wheelView5.setCyclic(true);
        wheelView5.setTextSize(18);
        wheelView6.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView6.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView6.setLineSpacingMultiplier(2.5f);
        wheelView6.setDividerType(WheelView.DividerType.WRAP);
        wheelView6.setCurrentItem(0);
        wheelView6.setItemsVisibleCount(5);
        wheelView6.setCyclic(true);
        wheelView6.setTextSize(18);
        //设置滚轮数据
        List<String> listHour = new ArrayList<>();//时
        for (int i = 0; i < 24; i++) {
            listHour.add(String.valueOf(i));
        }
        List<String> listMinute = new ArrayList<>();//分
        for (int i = 0; i < 60; i++) {
            listMinute.add(String.valueOf(i));
        }
        List<String> listSecond = new ArrayList<>();//秒
        for (int i = 0; i < 60; i++) {
            listSecond.add(String.valueOf(i));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listHour);
        wheelView4.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMinute);
        wheelView5.setAdapter(adapter2);
        WheelAdapter adapter3 = new ArrayWheelAdapter(listMinute);
        wheelView6.setAdapter(adapter3);
    }

    //选择时间单位弹框
    private void selTimeUnitDialog() {
        myTimeUnitDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_time_unit, null);
        myTimeUnitDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myTimeUnitDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogTimeUnitCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogTimeUnitRight);
        wheelView7 = inflate.findViewById(R.id.wheel_view1);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView7.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView7.setTextColorCenter(Color.parseColor("#0095FF"));
        wheelView7.setLineSpacingMultiplier(2.5f);
        wheelView7.setDividerType(WheelView.DividerType.WRAP);
        wheelView7.setCurrentItem(0);
        wheelView7.setItemsVisibleCount(4);
        wheelView7.setCyclic(false);
        wheelView7.setTextSize(18);
        //设置滚轮数据

        listUnit.add(getString(R.string.unit_year));
        listUnit.add(getString(R.string.unit_month));
        listUnit.add(getString(R.string.unit_day));
        listUnit.add(getString(R.string.add_time_hour));
        WheelAdapter adapter1 = new ArrayWheelAdapter(listUnit);
        wheelView7.setAdapter(adapter1);
    }

    //设置天
    private void setDayDate(int num) {
        List<String> listDay = new ArrayList<>();//日 默认显示1月31天
        for (int i = 0; i < num; i++) {
            listDay.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter3 = new ArrayWheelAdapter(listDay);
        wheelView3.setAdapter(adapter3);
    }

}